package esay.array;

import java.util.Arrays;

/**
 * 获取两个数组的交集
 * @author ruizhou
 * @date 24.02.2018
 */
public class IntersectionOfTwoArrays_Two {
    private static int[] intersect(int[] nums1, int[] nums2) {
        int nums1_len = nums1.length;
        int nums2_len = nums2.length;

        Arrays.sort(nums1);
        Arrays.sort(nums2);

        int[] intersects = new int[Math.min(nums1_len, nums2_len)];
        int i = 0, j = 0, k = 0;
        while (i < nums1_len && j < nums2_len) {
            if (nums1[i] > nums2[j]) {
                j++;
            } else if (nums1[i] < nums2[j]){
                i++;
            } else {
                intersects[k] = nums1[i];
                i++;
                j++;
                k++;
            }
        }

        return Arrays.copyOf(intersects, k);
    }

    public static void main(String[] args) {
//        int[] nums1 = {-2147483648,1,2,3};
//        int[] nums2 = {1,-2147483648,-2147483648};
        int[] nums1 = {3,1,2};
        int[] nums2 = {1,3};

        System.out.println(intersect(nums1, nums2));
    }
}
